package com.yhans.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yhans.dao.PermissionDao;
import com.yhans.dao.RoleDao;
import com.yhans.dao.UserDao;
import com.yhans.pojo.Permission;
import com.yhans.pojo.Role;
import com.yhans.pojo.User;
import com.yhans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询数据库获取用户信息和角色信息, 查询角色关联的权限信息
    public User findByUsername(String username) {

        User user = userDao.findByUsername(username);   //查询用户的基本信息 不包含用户的角色
        if (user==null){
            return null;
        }
        Integer id = user.getId(); //用户id
        //根据用户id查询对应角色
        Set<Role> roles =  roleDao.findByUserId(id);

        for (Role role : roles) {
            Integer roleId = role.getId();  //角色id
            //根据角色ID通过关联表 查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//角色关联权限
        }
        user.setRoles(roles);//用户关联角色
        return user;
    }
}
